
// Current data
var designObjectId = 0;
var designObjects = [];
var publicToken = null;
var privateToken = null;
var notes = '';
var mainStage = null;
var pixelsPerMetre = 30;
var shortenedPublicUrl = null;

// To load an image into the frontend - necessary before adding objects to the canvas
var preloadImage = function(url, callback) {
    var newImage = new Image();
    if (callback) {
        newImage.onload = function() {
            callback(newImage);
        };
    }
    newImage.src = url;
};
var preloadImageArray = function(urls, callback) {
    if (urls.length !== undefined && urls.length > 0) {
        var workingUrlsArray = urls.splice(0);
        var currentUrlToLoad = workingUrlsArray.pop();
        preloadImage(currentUrlToLoad, function() {
            if (workingUrlsArray.length > 0) {
                preloadImageArray(workingUrlsArray, callback);
            }
            else {
                callback();
            }
        });
    }
};

// For adding a button to the group, including shared (manual) styles
var addButtonToGroup = function(group, buttonImage) {
    buttonImage.on("mouseover", function() {
        document.body.style.cursor = "pointer";
    });
    buttonImage.on("mouseout", function() {
        document.body.style.cursor = "default";
    });

    group.add(buttonImage);
    buttonImage.hide();

    group.on("mouseover", function() {
        buttonImage.show();
        mainStage.draw();
    });
    group.on("mouseout", function() {
        buttonImage.hide();
        mainStage.draw();
    });
};

var deleteObjectById = function(id) {
    var newDesignObjects = [];

    $(designObjects).each(function(index, object) {
        if (object.id != id) {
            newDesignObjects.push(object);
        }
    });

    designObjects = newDesignObjects;
};

// For when a user drops a new object on the canvas

var addObjectToStage = function(type, imageUrl, x, y, width, height, allowResize) {
    designObjectId++;
    var newObject = {
        "id": designObjectId,
        "type": type,
        "width": width,
        "height": height,
        "rotation": 0,
        "x": x,
        "y": y
    };
    designObjects.push(newObject);

    // Need to preload images before adding to canvas
    // TODO Loading spinner needed here?
    preloadImage(imageUrl, function(preloadedImageElement) {

        var newLayer = new Kinetic.Layer();
        mainStage.add(newLayer);

        var objectGroup = new Kinetic.Group({
          x: x,
          y: y,
          draggable: true,
          rotatable: true
        });
        newLayer.add(objectGroup);

        objectGroup.on("mousedown touchstart", function(){
            this.getLayer().moveToTop();
        });
        objectGroup.on("dragstart", function() {
            this.moveToTop();
        });
        objectGroup.on("dragend", function() {
            newObject.x = objectGroup.attrs.x;
            newObject.y = objectGroup.attrs.y;
        });

        // Add image
        var objectImg = new Kinetic.Image({
            x: 0,
            y: 0,
            image: preloadedImageElement,
            width: width,
            height: height,
            name: "objectImg" // TODO Does this need to be unique?
        });
        objectGroup.add(objectImg);

        var iconSize = 40;
        var resizeImg = null;
        var rotateImg = null;
        var deleteImg = null;

        var fixButtonLocations = function() {
            deleteImg.setPosition(objectImg.attrs.width/2 + iconSize/2, objectImg.attrs.height/2 + 15);
            rotateImg.setPosition(objectImg.attrs.width/2 - iconSize/2, objectImg.attrs.height/2 + 15);
            resizeImg.setPosition(objectImg.attrs.width/2 - (1.5* iconSize), objectImg.attrs.height/2 + 15);
        };

        //
        // Add resize)
        //
        preloadImage("/images/new_resize.png", function(preloadedImageElement) {

            resizeImg = new Kinetic.Image({
                x: objectImg.attrs.width/2 - (1.5 * iconSize),
                y: objectImg.attrs.height/2 + 15,
                image: preloadedImageElement,
                width: iconSize,
                height: iconSize,
                name: "resizeImg",
                draggable: true
            });

            resizeImg.on("dragmove", function() {
                // Keep the designObjects list up to date.
                newObject.width = resizeImg.attrs.x + resizeImg.attrs.width;
                newObject.height = resizeImg.attrs.y + resizeImg.attrs.height;
				var resizeX = pixelsPerMetre;
				var resizeY = pixelsPerMetre;

                    // Resize the actual image and constrain resize to pixelsPerMetre by pixelsPerMetre
                    if((objectImg.attrs.height >= pixelsPerMetre) && (objectImg.attrs.width >= pixelsPerMetre) ){
                    		resizeX = resizeImg.attrs.x + iconSize + 40;
                    		resizeY = resizeImg.attrs.y + iconSize + 40;
                    		if(resizeX <= 0){
                    			resizeX = pixelsPerMetre;
                    		}
                    		if(resizeY <= 0){
                    			resizeY = pixelsPerMetre;
                    		}

                    }
                	else {
                		if(objectImg.attrs.height <= pixelsPerMetre){
                			resizeY = pixelsPerMetre;
                		}
	                	if(objectImg.attrs.width <= pixelsPerMetre){
                			resizeX = pixelsPerMetre;
                		}
                	}

	                if(resizeX < pixelsPerMetre){
                    	resizeX = pixelsPerMetre;
                    }
                    if(resizeY < pixelsPerMetre){
                    	resizeY = pixelsPerMetre;
                    }

                	objectImg.setSize(resizeX, resizeY);

                // Move the buttons
                //resizeImg.setPosition(resizeImg.attrs.x - resizeOffset, resizeImg.attrs.y - resizeOffset);
				fixButtonLocations();
				
                // Refresh
                newLayer.draw();
            });
            resizeImg.on("mousedown touchstart", function() {
                objectGroup.draggable(false);
                this.moveToTop();
            });
            resizeImg.on("dragend", function() {
                objectGroup.draggable(true);
                newLayer.draw();

                fixButtonLocations();
            });
            if(allowResize == true){
                addButtonToGroup(objectGroup, resizeImg);
            }
        });

        //
        // Add rotate
        //
        preloadImage("/images/new_rotate.png", function(preloadedImageElement) {
            var rotateSpeed = 30;

            rotateImg = new Kinetic.Image({
                x: objectImg.attrs.width/2 - iconSize/2,
                y: objectImg.attrs.height/2 + 15,
                image: preloadedImageElement,
                width: iconSize,
                height: iconSize,
                name: "rotateImg",
                draggable: true
            });

            // Handle the rotation
            var startEvent = null;
            var previousEvent = null;
            var currentMovementDegrees = 0;
            rotateImg.on("mousedown touchstart", function(event) {
				currentMovementDegrees = 0;

                objectGroup.draggable(false);
                objectGroup.moveToTop();

                startEvent = event;
                previousEvent = event;

                objectImg.setCenterOffset(objectImg.getWidth() / 2, objectImg.getHeight() / 2);
                objectImg.setPosition(objectImg.getWidth() / 2, objectImg.getHeight() / 2);
		
            });
            rotateImg.on("dragmove", function(event) {
                if (previousEvent.clientX - event.clientX > 0) {
                    objectImg.rotateDeg(2);
                    currentMovementDegrees += 2;
                }
                else {
                    objectImg.rotateDeg(-2);
                    currentMovementDegrees -= 2;
                }
                previousEvent = event;
                mainStage.draw();
			});
            rotateImg.on("dragend", function(event) {
                // Keep the designObjects list up to date.
                newObject.rotation += currentMovementDegrees;
                objectGroup.draggable(true);
                fixButtonLocations();
            });

            addButtonToGroup(objectGroup, rotateImg);
        });

        //
        // Add delete
        //
        preloadImage("/images/new_delete.png", function(preloadedImageElement) {

            deleteImg = new Kinetic.Image({
                x: objectImg.attrs.width/2 + iconSize/2,
                y: objectImg.attrs.height/2 + 15,
                image: preloadedImageElement,
                width: iconSize,
                height: iconSize,
                name: "deleteImg"
            });

            deleteImg.on("click", function() {
                // Keep the designObjects list up to date.
                deleteObjectById(newObject.id);

                newLayer.remove(objectGroup);
                mainStage.draw();
            });

            addButtonToGroup(objectGroup, deleteImg);
        });

        mainStage.draw();
    });
};

// Checks for canvas support
function checkCanvasSupport() {
	if(!document.createElement('canvas').getContext){
		$("body").css("background-color", "black");
		$("#mainContent").hide();
		$(".disclaimer").hide();
		$("#lightbox-browsers").bPopup({
			fadeSpeed: 'slow',
			followSpeed: 'fast',
			escClose: false,
			modalClose: false,
			position: [0, 200]
		});
	}
}
    
// Shortened link helpers
var getShortenedUrl = function(longUrl, callback) {
    $.getJSON(
        "http://api.bitly.com/v3/shorten?callback=?", 
        { 
            "apiKey": "R_161bd5efe236a8f895c7ffa4910490c5",
            "login": "playgroundideas",
            "longUrl": longUrl
        },
        function(response) {
            callback(response.data.url ? response.data.url : longUrl);
        }
    );
};
var setUpPublicUrl = function() {
    shortenedPublicUrl = showDesignBaseUrl + publicToken;
    getShortenedUrl(
        showDesignBaseUrl + publicToken,
        function(url) {
            shortenedPublicUrl = url;
        }
    );
};

$(document).ready(function() {
    var $ = jQuery;

    //
    // Core canvas handling
    //

    mainStage = new Kinetic.Stage({
        container: "canvas-container",
        width: $("#sizeInput").val() * pixelsPerMetre,
        height: $("#xInput").val() * pixelsPerMetre
    });
    $('.kineticjs-content').css('display', 'block');

    // Default gridlines to "on"
    $('.kineticjs-content').css('background-image', 'url(/images/grid.png)');
    $('.kineticjs-content').css('background-repeat', 'repeat');

    //
    // Save the design
    //
    var saveDesign = function(callback) {
        display_loading_screen("Saving...");
        
        var postContents = {
            name: $("#projectInput").val(),
            content: designObjects,
            description: notes,
            image: "",
            privateToken: privateToken,
            sizeWidth: $('#sizeInput').val(),
            sizeHeight: $('#xInput').val()
        };
        
        var doSave = function() {
            $.ajax({
                type: 'POST',
                url: 'save_design.php',
                data: postContents,
                success: function() {
                    hide_loading_screen();
                    
                    if (callback) {
                        callback();
                    }
                },
                dataType: 'json'
            });
        };
        
        // toDataURL() will throw an exception if the canvas is empty
        try {
            mainStage.toDataURL(function(dataUrl, mimeType, quality) {
                postContents.image = dataUrl;
                doSave(postContents);
            });
        }
        catch(error) {
            doSave(postContents);
        }
    };
    $("#saveButton").click(function() {
        saveDesign();
    });

    function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
    }

    // ***** END OBJECT SCROLLER *****

    // **** GRID LINES ****

	$("#toggleGridButton").click(function(){

		if($('.kineticjs-content').css('background-image') == 'none') {
			$('.kineticjs-content').css('background-image', 'url(/images/grid.png)');
			$('.kineticjs-content').css('background-repeat', 'repeat');
		}
		else{
			$('.kineticjs-content').css('background-image', '');
			$('.kineticjs-content').css('background-repeat', 'none');
		}

	});

    // **** GRID LINES ****

    //
    // Load the objects
    //
    $(objectLibrary.groups).each(function(index, group) {
        $("<div />")
            .addClass("canvas-footer-scrollerObjectGroup")
            .addClass(group.id)
            .addClass("objectGroup")
            .data("data", group)
            .append(
                $("<div />")
                    .addClass("objectGroupTitle")
                    .html(group.name)
            )
            .appendTo("#canvas-footer-" + group.layer + "Scroller .innerScroller");
    });

    var objectsToPreload = {};
    $(objectLibrary.objects).each(function(index, object) {
        objectsToPreload[object.id] = object.thumbnailImage;
    });
    loadImages(objectsToPreload, function() {

        //
        // All this stuff requires preloaded images
        //

        $(objectLibrary.objects).each(function(index, object) {
            $("<div />")
            .addClass("objectBrowserObject")
            .append(
                $("<img />")
                    .addClass(object.id)
                    .addClass("objectBrowserImg")
                    .data("data", object)
                    .attr("src", object.thumbnailImage)
            )
            .append(
                $("<div />")
                    .addClass("objectName")
                    .addClass(object.url === undefined ? null : "link")
                    .html(object.name)
                    .click(object.url === undefined ? null : function() {
                        window.open(object.url, "object-description", "width=600,height=400,scrollbars=yes");
                    })
            )
            .appendTo(".canvas-footer-scrollerObjectGroup." + object.group);
        });

        //
        // Handle dragging from the object browser
        //

        var currentObject = null;
        $("#canvas-footer-scroller-wrapper img").draggable({
            helper: "clone",
            appendTo: 'body',
            start: function(event, ui) {
                currentObject = $(event.currentTarget).data("data");
                setTimeout(function() {
                    $(".ui-draggable-dragging").attr("src", currentObject.image);
                }, 500);
            }
        });
        $("#canvas-container .kineticjs-content").droppable({
            drop: function(event, ui) {
                if (currentObject) {
                    var x = ui.position.left - $("#canvas-container .kineticjs-content").offset().left;
                    var y = ui.position.top - $("#canvas-container .kineticjs-content").offset().top;
                    addObjectToStage(currentObject.id, currentObject.image, x, y, (currentObject.width * pixelsPerMetre), (currentObject.height * pixelsPerMetre), currentObject.resizable);
                }
            }
        });

        //
        // Object browser scroller
        //
        var createObjectBrowser = function(layer) {
            var totalWidth = 0;
            var currentOffset = 0;
            var shiftDistance = 630;
            var windowSize = 705;

            $("#canvas-footer-" + layer + "Scroller .innerScroller img").each(function(index, element) {
                totalWidth += ($(element).width() + 28);
            })

            $("#canvas-footer-" + layer + "Scroller .innerScroller .objectGroup").each(function(index, element) {
                totalWidth += 16;
            });
            
            totalWidth -= 100; // For whatever reason, this seems to be the magic number the automatic calculations are out by

            $("#canvas-footer-" + layer + "Scroller .innerScroller").css("width", totalWidth + "px");
            $("#canvas-footer-" + layer + "Scroller").css("width", windowSize + "px");

            $("#canvas-footer-" + layer + "Scroller .innerScroller").css("margin-left", currentOffset + "px");
            $("#" + layer + "ScrollerPrevButton").click(function() {
                if (currentOffset - shiftDistance <= 0) {
                    currentOffset = 0;
                    $("#" + layer + "ScrollerPrevButton").hide();
                    $("#" + layer + "ScrollerNextButton").show();
                }
                else {
                    currentOffset -= shiftDistance;
                    $("#" + layer + "ScrollerPrevButton").show();
                    $("#" + layer + "ScrollerNextButton").show();
                }
                $("#canvas-footer-" + layer + "Scroller .innerScroller").animate({
                    "marginLeft": "-" + currentOffset + "px"
                }, 700);
                return false;
            });
            $("#" + layer + "ScrollerNextButton").click(function() {
                if (currentOffset + windowSize + shiftDistance >= totalWidth) {
                    currentOffset = totalWidth - windowSize;
                    $("#" + layer + "ScrollerNextButton").hide();
                    $("#" + layer + "ScrollerPrevButton").show();
                }
                else {
                    currentOffset += shiftDistance;
                    $("#" + layer + "ScrollerNextButton").show();
                    $("#" + layer + "ScrollerPrevButton").show();
                }
                $("#canvas-footer-" + layer + "Scroller .innerScroller").animate({
                    "marginLeft": "-" + currentOffset + "px"
                }, 700);
                return false;
            });
        };
        createObjectBrowser("playground");
        createObjectBrowser("landscape");

        //
        // Switch between scrollers
        //
        $("#canvas-footer-playground-group").click(function() {
            $("#canvas-footer-playground-group").addClass("selected");
            $("#canvas-footer-landscape-group").removeClass("selected");

            $("#landscapeScrollerPrevButton").hide();
            $("#landscapeScrollerNextButton").hide();
            $("#canvas-footer-landscapeScroller").hide();

            $("#playgroundScrollerNextButton").show();
            $("#canvas-footer-playgroundScroller").show();
        });
        $("#canvas-footer-landscape-group").click(function() {
            $("#canvas-footer-landscape-group").addClass("selected");
            $("#canvas-footer-playground-group").removeClass("selected");

            $("#playgroundScrollerPrevButton").hide();
            $("#playgroundScrollerNextButton").hide();
            $("#canvas-footer-playgroundScroller").hide();

            $("#landscapeScrollerNextButton").show();
            $("#canvas-footer-landscapeScroller").show();
        });

        $("#playgroundScrollerPrevButton").hide();
        $("#landscapeScrollerPrevButton").hide();
        $("#landscapeScrollerNextButton").hide();
        $("#canvas-footer-landscapeScroller").hide();
    });

    //
    // Change canvas size
    //
    $("#sizeInput").blur(resizeCanvasFromFields);
    $("#xInput").blur(resizeCanvasFromFields);
    
    //
    // Lightboxes
    //
    
    // Welcome
    $("#welecomeLegalCheckbox").click(function() {
        if( $('#welecomeLegalCheckbox').is(':checked') ){
            $('#welcomeGoPlayButton').removeClass('off');
        } else {
            $('#welcomeGoPlayButton').addClass('off')
        }
    });
    $("#welcomeGoPlayButton").click(function() {
        var projectName = $('#welcomeNameInput').val();
        var length = $('#welcomeLength').val();
        var width = $('#welcomeWidth').val();
        var email = $('#welcomeEmailInput').val();
        if (length == '' || width =='' || projectName == '' || email == '' || !IsNumeric(length) || !IsNumeric(width)) {
            $('#welcomeLength').removeClass('error');
            $('#welcomeWidth').removeClass('error');
            $('#welcomeNameInput').removeClass('error');
            $('#welcomeEmailInput').removeClass('error');

            if (length == '' || !IsNumeric(length)) {
                $('#welcomeLength').addClass('error');
				$('#welcomeLength').val('');
                $('#welcomeLength').attr("placeholder", "Numeric please");
            }
            if (width == '' || !IsNumeric(width)){
                $('#welcomeWidth').addClass('error');
				$('#welcomeWidth').val('');
                $('#welcomeWidth').attr("placeholder", "Numeric please");
            }
            if (projectName == '') {
                $('#welcomeNameInput').addClass('error');
                $('#welcomeNameInput').attr("placeholder", "Please complete");
            }
            if (email == '') {
                $('#welcomeEmailInput').addClass('error');
                $('#welcomeEmailInput').attr("placeholder", "Please complete");
            }
        }
        else {
            $('#projectInput').val(projectName);
            
            $('#sizeInput').val(width);
            $('#xInput').val(length);
            resizeCanvasFromFields();
            
            $("#lightbox-splashScreen").bPopup().close();

            var postContents = {
                 name: projectName,
                 content: designObjects,
                 description: "",
                 email: email,
                 sizeWidth: width,
                 sizeHeight: length
            };
     
             display_loading_screen("Creating...");
             $.ajax({
                 type: 'POST',
                 url: 'save_design.php',
                 data: postContents,
                 success: function(data) {
     
                     publicToken = data.publicToken;
                     privateToken = data.privateToken;
                     
                     display_loading_screen("Sending email...");
                     $.ajax({
                         type: 'POST',
                         url: 'send_email.php',
                         data: {
                             address: email,
                             privateToken: privateToken,
                             publicToken: publicToken,
                             emailType: "create"
                         },
                         success: function(data) {
                            hide_loading_screen();
                            
                            setUpPublicUrl();
                         },
                         dataType: 'json'
                     });
                 },
                 dataType: 'json'
             });
        }
    });

    // Notes
    $("#canvas-header-menu img#addNoteButton").live('click', function(e) {
        // Pre-pop only if there's some notes to show, otherwise leave the default text
        if (notes) {
            $('#notesLightBoxTextArea').val(notes);
        }
        
        $("#lightbox-addNotes").bPopup({
            fadeSpeed: 'slow',
            followSpeed: 'fast',
            escClose: false,
            modalClose: false
        });
    });
    $("#notesLightBoxCloseButton").click(function() {
        notes = $('#notesLightBoxTextArea').val();
        $("#lightbox-addNotes").bPopup().close();
    });
    
    // Share
    var neverShown = true;
    $("#canvas-header-menu img#exportButton").live('click', function(e) {
        
        // Always save before sharing
        saveDesign(function() {
            $("#lightbox-exportDesign").bPopup({
                fadeSpeed: 'slow',
                followSpeed: 'fast'
            }, function() {
                setTimeout(function() {
                    $(window).resize();
                }, 1);
            });
    
            if (neverShown) {
                neverShown = false;
                
                // Public URL stuff
                $("#exportDesign-container").prepend("<div class='link-container' id='share-link'>Link to share your playground with others:<br /><input class='cool-textbox' type='text' readonly value='" + shortenedPublicUrl + "' /><span id='share-link-copy'>Copy link</span></div>");
                $('#share-link-copy').zclip({
                    path: '/js/ZeroClipboard.swf',
                    copy: shortenedPublicUrl,
                    afterCopy: function() {}
                });
                
                // Private URL stuff
                $("#exportDesign-container").prepend("<div class='link-container' id='edit-link'>Link to edit your playground at a later stage: <br /><input class='cool-textbox' type='text' readonly value='" + editBaseUrl + privateToken + "' /><span id='edit-link-copy'>Copy link</span></div>");
                $('#edit-link-copy').zclip({
                    path: '/js/ZeroClipboard.swf',
                    copy: editBaseUrl + privateToken,
                    afterCopy: function() {}
                });
                
                // Header
                $("#exportDesign-container").prepend("<h2 id='export-header'>Export your design</h2>");
                
                // Select text on click
                $(".link-container input").click(function() {
                    $(this).select();
                });
                
                // Facebook integration
                $("#fb-like-container").append(
                    $("<div />")
                        .addClass("fb-like")
                        .attr("data-href", showDesignBaseUrl + publicToken)
                        .attr("data-send", "false")
                        .attr("data-show-faces", "true")
						.attr("data-layout", "button_count")			
                );
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
                var firstScript = document.getElementsByTagName('script')[0];
                firstScript.parentNode.insertBefore(script, firstScript);
                
                // Twitter integration
                $("#twitter-tweet-container").append(
                    $("<a />")
                        .addClass("twitter-share-button")
                        .attr("href", "http://twitter.com/share")
                        .attr("data-url", shortenedPublicUrl)
                        .attr("data-text", "I just created a sweet playground design. Love it! Check it out.")
                        .attr("data-hashtags", "playgroundideas")
                        .html("Tweet")
                );
                twttr.widgets.load();
            }
        });
    });
    $("#export-print").click(function() {
        mainStage.toDataURL(function(dataUrl) {
            window.open(dataUrl);
        });
    });
    $("#show-export-email-options").click(function() {
        $("#show-export-email-options").hide();
        $("#export-email-address").show();
        $("#send-export-email").show();
        
        $("#send-export-email").click(function() {
            display_loading_screen("Sending email...");
            
            if ($("#export-email-address").val() != "") {
                $.ajax({
                    type: 'POST',
                    url: 'send_email.php',
                    data: {
                        address: $("#export-email-address").val(),
                        privateToken: privateToken,
                        publicToken: publicToken,
                        emailType: "share"
                    },
                    success: function(data) {
                        hide_loading_screen();
                        
                        $("#export-email-address").val("");
                        $("#show-export-email-options").show();
                        $("#export-email-address").hide();
                        $("#send-export-email").hide();
                    },
                    dataType: 'json'
                });
            }
        });
    });

     // Help
    $("#canvas-header-menu img#userHelpButton").live('click', function(e) {
        $("#lightbox-userHelp").bPopup({
            fadeSpeed: 'slow',
            followSpeed: 'fast'
        });
    });
    
    // Important stuff
    if (window.addEventListener) {
        var neverShown = true;
        var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
        window.addEventListener("keydown", function(e){
            if (neverShown) {
                kkeys.push(e.keyCode);
                if (kkeys.toString().indexOf(konami) >= 0) {
                    $('.kineticjs-content').css('background-image', 'url(/images/hotrod.jpg)');
                    $('.kineticjs-content').css('background-repeat', 'repeat');
                    
                    $("<div />")
                        .css("background-color", "white")
                        .css("padding", "10px")
                        .css("border-radius", "8px")
                        .hide()
                        .append(
                            $("<iframe width=\"420\" height=\"315\" src=\"http://www.youtube.com/embed/rW0w0ErlgAM?autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>")
                        )
                        .appendTo("body")
                        .bPopup({
                            fadeSpeed: 'slow',
                            followSpeed: 'fast'
                        });
                    
                    neverShown = false;
                }
            }
        }, true);
    }

}); // End $(document).ready

// Simple helper to check if numeric and not blank
function IsNumeric(n)
{
    return !isNaN(parseFloat(n)) && isFinite(n);
}

// **** LOADING SCREEN  ****
function display_loading_screen(headerTxt, msg)
{
    document.getElementById("loading_screen").style.display = 'block';
    $("#loading_text").text(msg ? msg : "");
    $("#loading_header").text(headerTxt);
}
function hide_loading_screen()
{
  document.getElementById("loading_screen").style.display = 'none';
}
// **** END LOADING SCREEN *****

// Simple helper for loading config for an item type
var getObjectConfigById = function(id) {
    var foundElement = null;

    $(objectLibrary.objects).each(function(index, element) {
        if (element.id == id) {
            foundElement = element;
        }
    });

    return foundElement;
};

// Resize the canvas based on what's in the toolbar fields
var resizeCanvasFromFields = function() {
    if(IsNumeric($('#sizeInput').val()) && IsNumeric($('#xInput').val()))
    {
        mainStage.setSize($("#sizeInput").val() * pixelsPerMetre, $("#xInput").val() * pixelsPerMetre);
    }
};